Ext.ns('Wlanauth.system');

Wlanauth.system.AnalysisPanel = Ext.extend(Ext.Panel,{
	title:'流量查询',
	constructor:function(config){
		Ext.apply(this,config);
		
		var fp = new Wlanauth.BaseFormPanel({
			frame:true,
			border:false,
			layout:'column',
			items:[{
				xtype:'displayfield',
				value:'年'
			},{
				xtype:'displayfield',
				value:'月'
			},{
				xtype:'displayfield',
				value:'日'
			}]
		});
		
		function octRender(val,meta,record,row,col,store){
			return Ext.util.Format.number(Math.round(val/1024/1024*100)/100,'0,000.00')
		}
		var sm = new Ext.grid.CheckboxSelectionModel();
		this.grid = new Ext.grid.GridPanel({
			border:false,
			loadMask:true,
			sm:sm,
			store:new Ext.data.JsonStore({
				url:'radAcct!simpleAnalysis.action',
				totalProperty:'data',
				autoLoad:true,
				root:'rows',
				fields:['id','date','sumOct','sumOct2','sumUser']
				
			}),
			cm:new Ext.grid.ColumnModel({
				columns:[new Ext.grid.RowNumberer(),sm,
				    {header:'日期',dataIndex:'date',width:120,renderer:this.dateRender},
				    {header:'总流量(Mb)',dataIndex:'sumOct',width:150,renderer:octRender},
					{header:'计费流量(Mb)',dataIndex:'sumOct2',sortable:true,renderer:octRender},
				    {header:'使用人数',dataIndex:'sumUser',width:90,sortable:true,renderer:Ext.util.Format.numberRenderer('0,000')},
				   ]}),
			 viewConfig: {
	            forceFit: true
			 }
		});
		var fp = new TimePanelFormPanel();
		Wlanauth.system.AnalysisPanel.superclass.constructor.call(this,{
			border:false,
			tbar:['按条件查询',{
				xtype:'displayfield',
				width:40,
				value:':'
			},fp,{
				text:'查询',
				iconCls:'search',
				handler:function(){
					var params = fp.getForm().getValues();
					this.grid.getStore().reload({params:params});
				},
				scope:this
			},'->',{
				text:'图表',
				iconCls:'class',
				handler:this.viewChart,
				scope:this
			}],
			layout:'fit',
			items:[this.grid]
		});
	},
	dateRender:function(val,meta,r,store){
		return '<a href="javascript:void(0)" onclick="Wlanauth.system.viewChildren(\''+val+'\')" title="点击查看总趋势">'+val+'</a>';
	},
	viewChart:function(){
		var rs = this.grid.getStore().getRange();
		var rows = [];
		for(var i=0;i<rs.length;i++){
			var r = rs[i];
			rows.push({
				sumOct:r.get('sumOct'),
				sumOct2:r.get('sumOct2'),
				sumUser:r.get('sumUser'),
				date:r.get('date')
			});
		}
		var win = Wlanauth.system.newChartWin();
		win.setChartData(rows);
	}
});

Ext.reg('wlanauth.system.analysispanel',Wlanauth.system.AnalysisPanel);
/**
 * 创建新窗口
 */
Wlanauth.system.newChartWin = function(){
	
	var win = new Ext.Window({
		width:650,
		height:400,
		resizable:true,
		closeAction:'close',
		title:'流量图',
		padding:5,
		parentDate:'',
		html:'<div style="width:100%;height:100%" id="'+id+'"></div>',
		setChartData:function(data){
			if(data==null||data.length<1) return;
			var chart = this.chart;
			var serieOct = chart.series[0];
			var serieOct2 = chart.series[1];
			var serieUser = chart.series[2];
			var xAxis = chart.xAxis[0];
			var octArr = [];
			var octArr2 = [];
			var sumUserArr = [];
			var categories = [];
			for(var i=0;i<data.length;i++){
				var r = data[i];
				var x = r.date;
				var parentDate = win.parentDate;
				var cat = x.substring(parentDate.length+1);
				if(parentDate.length==4){
					cat+='月';
				} else if(parentDate.length==7){
					cat+='日';
				} else if(parentDate.length==10){
					cat+='时';
				} 
				categories.push(cat);
				
				var oct = Math.round(r.sumOct/1024/1024*100)/100;
				var oct2 = Math.round(r.sumOct2/1024/1024*100)/100;
				octArr.push(oct);
				octArr2.push(oct2);
				sumUserArr.push({
					name:cat,
					y:r.sumUser,
					oct:oct,
					oct2:oct2
				});
			}
			serieOct.setData(octArr);
			serieOct2.setData(octArr2);
			serieUser.setData(sumUserArr);
			xAxis.setCategories(categories);
		},
		listeners:{
			'bodyresize':function(panel,width,height){
				if(panel.chart){
					var t = 2*panel.padding;
					panel.chart.setSize(width-t,height-t);
					
				}
			}
		}
	});
	win.show();
	var chart = renderOctetChart(id);
	win.chart = chart;
	return win;
}

Wlanauth.system.viewChildren = function(val){
	var win =  Wlanauth.system.newChartWin();
	win.parentDate = val;
	win.setTitle('使用情况 -- <font style="color:red">'+val+'</font>加载中...');
	Ext.Ajax.request({
		url:'radAcct!simpleAnalysisChildren.action?parentDateStr='+val,
		success:function(response,opts){
			var r = Ext.decode(response.responseText);
			if(r.success){
				win.setChartData(r.rows);
				win.setTitle('使用情况 -- <font style="color:red">'+val+'</font>');
			} else {
				win.setTitle('<font color="red">加载出错</font>');
			}
		}
	});
}
/**
 * 日期表单
 */
TimePanelFormPanel=Ext.extend(Ext.form.FormPanel,{
	baseCls:'x-plant',
	constructor:function(){
		
		var defaultYears = [['任意','']];
		var year = new Date().getFullYear();
		for(var i=0;i<=5;i++){
			var y = year-i;
			if(y<2012){break;}
			defaultYears.push([y,y]);
		}
		function initdatas(len){
			var data = [['任意','']];
			for(var i=1;i<=len;i++){
				var tmp = (i<10?'0'+i:''+i);
				data.push([tmp,tmp]);
			}
			return data;
		}
		var months = initdatas(12);
		var days =initdatas(31);
		
		TimePanelFormPanel.superclass.constructor.call(this,{
			border:false,
			defaults:{border:false},
			layout:'column',
			items:[{
				xtype:'localcombo',
				data:defaultYears,
				name:'year',
				editable:true,
				width:80,
				regex:/[0-9]?/,
				regexText:'必须为数字',
				listeners:{'select':this.changeDay}
			},{
				xtype:'label',
				html:'&nbsp;&nbsp;年&nbsp;&nbsp; '
			},{
				xtype:'localcombo',
				name:'month',
				data:months,
				editable:true,
				width:80,
				regex:/[0-9]?/,
				regexText:'必须为数字',
				listeners:{'select':this.changeDay}
			},{
				xtype:'label',
				html:'&nbsp;&nbsp;月&nbsp;&nbsp;'
			},{
				xtype:'localcombo',
				name:'day',
				data:days,
				editable:true,
				width:80,
				regex:/[0-9]?/,
				regexText:'必须为数字'
			},{
				xtype:'label',
				html:'&nbsp;&nbsp;日&nbsp;&nbsp;'
			}]
		});
	 },
	 /**
		 * 年月变化，改变日
		 */
	 changeDay:function(){
		 // 每个月的初始天数
	　         MonDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];   
	　         var year=this.ownerCt.findByType("combo")[0].getValue();
	　         var month=this.ownerCt.findByType("combo")[1].getValue();
	　         var n = MonDays[month - 1];   
	　         if(month=='2'&&isLeapYear(year)){
	　        	 n++;
	　         }
	　         if(!n) n=31;
	　        var data = [['任意','']];
	　         // 填充日期下拉框
	　         for(var i=1; i<=n; i++) {
	　        	var tmp = (i<10?'0'+i:''+i);
	    　　        data.push([tmp,tmp]);
	    　　 } 
	     var _store = this.ownerCt.findByType("combo")[2].getStore();
         _store.loadData(data);
	        
	 },
	 /**
		 * 判断是否闰年
		 * 
		 * @param {}
		 *            year
		 * @return {}
		 */
	 isLeapYear:function (year)  {
		 return( year%4==0 || (year%100 ==0 && year%400 == 0));   
	 }  
});


/**
 * 月流量统计图
 * @param elId
 */
function renderOctetChart(elId){
	
	return new Highcharts.Chart({
		chart: {
			renderTo: elId,
			//type: 'column',
			backgroundColor:'none',
			borderColor: '#aaa',
		    borderWidth: 1,
		    zoomType: 'xy'
		},
		title: {
			text: '流量概览'
		},
		
		credits: {
			enabled: false
		},
		xAxis: {
			categories: [],
			labels: {
				rotation: -45,
				align: 'right',
				style: {
					font: 'normal 13px Verdana, sans-serif'
				}
			}
		},
		yAxis: [{
			min: 0,
			title: {
				text: '流量(M)'
			}
		},{
			title: {
				text: '使用情况',
				style: {
					color: '#89A54E'
				}
			},
			labels: {
				formatter: function() {
					return this.value +' 人';
				},
				style: {
					color: '#4572A7'
				}
			},
			min:0,
			minRange:1,
			tickInterval:100, //坐标轴单位宽度  
			opposite: true
		}],
		
		tooltip: {
			formatter: function() {
				if (this.point.name) { // the pie chart
					return '<span style="color:blue">'+this.point.name+'</span>: <span style="color:red">'+ this.y+'</span> 人使用<br/>'
						+'实际流量: <span style="color:red">'+this.point['oct']+'</span> M<br/>'
						+'计费流量:<span style="color:red">'+this.point['oct2']+'</span> M';
				} else {
					return this.series.name+'<br/>'+
					this.x +': '+ this.y +' M';y;
				}
				
			}
		},
		plotOptions: {
			column: {
				pointPadding: 0.2,
				borderWidth: 0
			}
		},
		series: [{
			name: '总流量',
			type: 'column',
			data:[],
			type:'areaspline'
		},{
			name: '比率流量',
			type: 'column',
			data: []
		},{
			type: 'spline',
			name: '使用情况',
			data: [],
			yAxis: 1
		}]
	});
	
}
